﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using WindowsPhonePostClient;
using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.Windows.Controls.Primitives;
using Microsoft.Phone.Controls.Primitives;



namespace MeetingFinder
{
    public partial class EditMeetingForm : PhoneApplicationPage
    {
        private ObservableCollection<ServerUserMeetingSuggestion> newUserSuggestionList;
        private ObservableCollection<ServerUserMeetingSuggestion> currentUserSuggestionList;
        private ServerUserMeetingSuggestion selectedSuggestion;
        private Popup popup = new Popup();
        private bool suggestionRetreived = false;

        public EditMeetingForm()
        {
            var received = App.Current as App;

            //pull list of current suggestions
            WebClient getCurrentUserSuggestionItems = new WebClient();
            getCurrentUserSuggestionItems.DownloadStringCompleted += (senderN, eN) =>
            {
                if (eN.Error == null)
                {
                    var result = eN.Result;
                    currentUserSuggestionList = JsonConvert.DeserializeObject<ObservableCollection<ServerUserMeetingSuggestion>>(result);

                    //post notification checked to server
                    string notificationID = NavigationContext.QueryString["notificationid"];
                    //check if navigated from notification page
                    if (notificationID != "notnotification")
                    {
                        Dictionary<string, object> checkedNotifaction = new Dictionary<string, object>();
                        checkedNotifaction.Add("notification_id", notificationID);//pass notification id via URI

                        PostClient checkedNotification = new PostClient(checkedNotifaction);
                        checkedNotification.DownloadStringAsync(new Uri(StringConstants._serverAddress + StringConstants._postUpdateNotificationAPI, UriKind.Absolute));
                    
                        ServerNotificationItem readNotification = null;
                        //moving from unread to read list
                        foreach(ServerNotificationItem notificationItem in received._unreadNotificationItemList)
                            if (notificationItem._id == notificationID)
                                readNotification = notificationItem;

                        if (readNotification != null)
                        {
                            received._notificationItemList.Add(readNotification);
                            received._unreadNotificationItemList.Remove(readNotification);
                        }
                            
                    }

                    //get user's choice (ranking) for each user suggestion item
                    WebClient getUserChoice = new WebClient();
                    getUserChoice.DownloadStringCompleted += (senderUC, eUC) =>
                    {
                        if (eUC.Error == null)
                        {
                            var userChoiceResult = eUC.Result;
                            var userChoiceList = JsonConvert.DeserializeObject<List<ServerUserChoiceItem>>(userChoiceResult);

                            //go through list of existing suggestion items, set state(user ranking) 
                            foreach (ServerUserChoiceItem userchoice in userChoiceList)
                            {
                                for (int i = 0; i < currentUserSuggestionList.Count; i++)
                                {
                                    if (currentUserSuggestionList[i]._userSuggestionItemId == userchoice._userSuggestionItemId)
                                        if (userchoice._state == "-1")
                                            currentUserSuggestionList[i]._state = "3";
                                        else
                                            currentUserSuggestionList[i]._state = userchoice._state;
                                }
                            }

                            //initialize page components
                            InitializeComponent();

                            editFormProjectGroup.Text = received._editFormItemSelected._groupName;
                            editFormTitle.Text = received._editFormItemSelected._meetingName;
                            editFormDescription.Text = received._editFormItemSelected._meetingDescription;
                            editFormLocationInput.Text = received._editFormItemSelected._meetingLocation;

                            this.editFormCurrentSuggestionList.ItemsSource = currentUserSuggestionList;
                            this.editFormNewSuggestionList.ItemsSource = newUserSuggestionList;
                        }
                    };
                    getUserChoice.DownloadStringAsync(new Uri(StringConstants._serverAddress + StringConstants._getMeetingItemsChoiceAPI + received._userID + "/" + received._editFormItemSelected._meetingItemID, UriKind.Absolute));

                }
            };
            getCurrentUserSuggestionItems.DownloadStringAsync(new Uri(StringConstants._serverAddress + StringConstants._getCurrentMeetingItemsAPI + received._editFormItemSelected._meetingItemID, UriKind.Absolute));



            newUserSuggestionList = new ObservableCollection<ServerUserMeetingSuggestion>();
            currentUserSuggestionList = new ObservableCollection<ServerUserMeetingSuggestion>();

            
        }


        private void editFormsubmitButton_Click(object sender, RoutedEventArgs e)
        {
            var received = App.Current as App;
            string meetingDetailsUpdateMessage;
            bool meetingDetailsChanged = true;
            string errorMessage = StringConstants.meetingDetailsNotChangedMsg;


            if (this.editFormDescription.Text == received._editFormItemSelected._meetingDescription && this.editFormTitle.Text == received._editFormItemSelected._meetingName)
                meetingDetailsChanged = false;

            if (meetingDetailsChanged || newUserSuggestionList.Count != 0)
            {

                //send updated meeting details only if user is the meeting creator
                if (received._editFormItemSelected._meetingCreatorID == received._userID)//false condition for testing
                {
                    string time = "";
                    string location = "";

                    if (suggestionRetreived == true)
                    {
                        time = this.editFormtimeInput.Value.ToString();
                        location = this.editFormdateInput.Value.ToString();
                    }

                    //send updated meeting details
                    Dictionary<string, object> updatedMeeting = new Dictionary<string, object>();

                    updatedMeeting.Add("title", editFormTitle.Text);
                    updatedMeeting.Add("content", editFormDescription.Text);
                    updatedMeeting.Add("creator_id", received._editFormItemSelected._meetingCreatorID);
                    updatedMeeting.Add("group_id", received._editFormItemSelected._groupID);
                    updatedMeeting.Add("is_confirmed", StringConstants._is_confirmed_FALSE);
                    updatedMeeting.Add("is_completed", StringConstants.is_completed_FALSE);
                    updatedMeeting.Add("f_location", time);
                    updatedMeeting.Add("f_time", location);

                    PostClient updatedMeetingProxy = new PostClient(updatedMeeting);
                    updatedMeetingProxy.DownloadStringAsync(new Uri(StringConstants._serverAddress + StringConstants._postUpdateMeetingDetailsAPI, UriKind.Absolute));

                    meetingDetailsUpdateMessage = StringConstants.meetingDetailsUpdated;

                }
                else
                {
                    //informing user meeting details only changed by owner, user suggestion is updated
                    meetingDetailsUpdateMessage = StringConstants.meetingDetailsNotUpdated;
                }

                bool stateIsValid = true;

                //check if all new meeting items have state(ranking) else popup telling user to set
                foreach (ServerUserMeetingSuggestion meetingSuggestionItem in newUserSuggestionList)
                    if (Convert.ToInt32(meetingSuggestionItem._state) < 0 || Convert.ToInt32(meetingSuggestionItem._state) > 5 || meetingSuggestionItem._state == null)
                        stateIsValid = false;

                if (stateIsValid)
                {
                    //send new user suggested meeting timings
                    foreach (ServerUserMeetingSuggestion meetingSuggestion in newUserSuggestionList)
                    {
                        //send new user suggested meeting item
                        Dictionary<string, object> userSuggestion = new Dictionary<string, object>();

                        userSuggestion.Add("meeting_id", received._editFormItemSelected._meetingItemID);
                        userSuggestion.Add("time", meetingSuggestion._time);
                        userSuggestion.Add("location", meetingSuggestion._location);
                        userSuggestion.Add("user_id", received._userID);


                        PostClient newUserSuggestionProxy = new PostClient(userSuggestion);
                        newUserSuggestionProxy.DownloadStringAsync(new Uri(StringConstants._serverAddress + StringConstants._postNewUserSuggestionItemAPI, UriKind.Absolute));

                        //get new meeting suggestion item id
                        string userSuggestionItemID;
                        newUserSuggestionProxy.DownloadStringCompleted += (senderUS, eUS) =>
                        {
                            if (eUS.Error == null)
                            {
                                var result = eUS.Result;
                                var test = result.Split('\t', '\n');
                                userSuggestionItemID = result.Split('\t', '\n')[4];

                                //send new user choice
                                Dictionary<string, object> userChoice = new Dictionary<string, object>();

                                userChoice.Add("item_id", userSuggestionItemID);
                                userChoice.Add("user_id", received._userID);
                                userChoice.Add("state", meetingSuggestion._state);

                                PostClient userChoiceProxy = new PostClient(userChoice);
                                userChoiceProxy.DownloadStringAsync(new Uri(StringConstants._serverAddress + StringConstants._postUpdateUserSuggestionChoiceAPI, UriKind.Absolute));


                            }
                        };
                    }

                    //post updated STATE(RANKING) on current meeting timings
                    foreach (ServerUserMeetingSuggestion meetingSuggestion in currentUserSuggestionList)
                    {
                        Dictionary<string, object> userChoiceUpdate = new Dictionary<string, object>();

                        userChoiceUpdate.Add("item_id", meetingSuggestion._userSuggestionItemId);
                        userChoiceUpdate.Add("user_id", received._userID);
                        userChoiceUpdate.Add("state", meetingSuggestion._state);

                        PostClient currentUserSuggestionProxy = new PostClient(userChoiceUpdate);
                        currentUserSuggestionProxy.DownloadStringAsync(new Uri(StringConstants._serverAddress + StringConstants._postUpdateUserSuggestionChoiceAPI, UriKind.Absolute));

                        currentUserSuggestionProxy.DownloadStringCompleted += (senderUS, eUS) =>
                        {
                            if (eUS.Error == null)
                            {
                                var result = eUS.Result;
                            }
                        };
                    }

                    popup.Height = 300;
                    popup.Width = 400;
                    popup.VerticalOffset = 100;
                    EditMeetingFormPopup control = new EditMeetingFormPopup();
                    popup.Child = control;
                    popup.IsOpen = true;

                    control.messageBox.Text = meetingDetailsUpdateMessage + "\n" + "Meeting Suggestions submitted";

                    control.btnOK.Click += (s, args) =>
                    {
                        popup.IsOpen = false;
                        this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                    };
                }
                else
                {
                    popup.Height = 300;
                    popup.Width = 400;
                    popup.VerticalOffset = 100;
                    EditMeetingFormPopup control = new EditMeetingFormPopup();
                    popup.Child = control;
                    popup.IsOpen = true;

                    control.messageBox.Text = "Please enter a Preferences for all Meeting Suggestions within the rage 0-5";

                    control.btnOK.Click += (s, args) =>
                    {
                        popup.IsOpen = false;
                    };
                }
            }
            else
            {
                popup.Height = 300;
                popup.Width = 400;
                popup.VerticalOffset = 100;
                EditMeetingFormPopup control = new EditMeetingFormPopup();
                popup.Child = control;
                popup.IsOpen = true;

                control.messageBox.Text = errorMessage;

                control.btnOK.Click += (s, args) =>
                {
                    popup.IsOpen = false;
                };
            }

            //show popup informing user submitted and return to main page
        }

        private void editFormAddUserSuggestionButton_Click(object sender, RoutedEventArgs e)
        {
            if (newUserSuggestionList.Count == 0)
            {
                ServerUserMeetingSuggestion userMeetingSuggestion = new ServerUserMeetingSuggestion();

                //get ID form item passed
                userMeetingSuggestion._location = editFormLocationInput.Text;//get form item passed
                userMeetingSuggestion._time = getDateTimeString();

                //need to add a check to ensure identical user suggestions not added
                newUserSuggestionList.Add(userMeetingSuggestion);
            }
            else
            {
                bool userSuggestionExists = false;

                //check if new user suggestion already exists in new user list
                foreach (ServerUserMeetingSuggestion currentSuggestion in newUserSuggestionList)
                {
                    if (currentSuggestion._time == getDateTimeString() && currentSuggestion._location == editFormLocationInput.Text)
                        userSuggestionExists = true;
                }
                //check if new user suggestion already exists in current user list
                foreach (ServerUserMeetingSuggestion currentSuggestion in currentUserSuggestionList)
                {
                    if (currentSuggestion._time == getDateTimeString() && currentSuggestion._location == editFormLocationInput.Text)
                        userSuggestionExists = true;
                }

                if (!userSuggestionExists)
                {
                    ServerUserMeetingSuggestion userMeetingSuggestion = new ServerUserMeetingSuggestion();

                    //get ID form item passed
                    userMeetingSuggestion._location = editFormLocationInput.Text;//get form item passed
                    userMeetingSuggestion._time = getDateTimeString();

                    //need to add a check to ensure identical user suggestions not added
                    newUserSuggestionList.Add(userMeetingSuggestion);
                }
                else
                {
                    popup.Height = 300;
                    popup.Width = 400;
                    popup.VerticalOffset = 100;
                    EditMeetingFormPopup control = new EditMeetingFormPopup();
                    popup.Child = control;
                    popup.IsOpen = true;

                    control.messageBox.Text = "Meeting Suggestion Exists";

                    control.btnOK.Click += (s, args) =>
                    {
                        popup.IsOpen = false;
                    };
                }
            }
        }

        private string getDateTimeString()
        {
            string dateTimeString = editFormdateInput.ValueString + " " + editFormtimeInput.ValueString;
            DateTime meetingDateTime = Convert.ToDateTime(dateTimeString);
            string time = String.Format("{0:u}", meetingDateTime);

            return time.Substring(0, time.Length - 1);//to remove special character 'Z' at the end
        }

        private void getSuggestionButton_Click(object sender, RoutedEventArgs e)
        {
            var received = App.Current as App;

            if (newUserSuggestionList.Count == 0)
            {
                //pull suggestion
                WebClient getMeetingSuggestion = new WebClient();
                getMeetingSuggestion.DownloadStringCompleted += (senderMS, eMS) =>
                {
                    if (eMS.Error == null)
                    {
                        var meetingSuggestionResult = eMS.Result;
                        var meetingSuggestionList = JsonConvert.DeserializeObject<List<String>>(meetingSuggestionResult);

                        suggestionRetreived = true;

                        //search current list for meeting item and add to serverSuggestionList
                        //users not allowed to use get suggestion if new items added
                        List<ServerUserMeetingSuggestion> serverSuggestionList = new List<ServerUserMeetingSuggestion>();

                        foreach (string suggestedItem in meetingSuggestionList)
                        {
                            //searching current list
                            foreach (ServerUserMeetingSuggestion currentSuggestionItem in currentUserSuggestionList)
                                if (currentSuggestionItem._userSuggestionItemId == suggestedItem)
                                    serverSuggestionList.Add(currentSuggestionItem);
                        }

                        //setting recommended meeting item
                        List<ServerUserMeetingSuggestion> recommendedSuggestionList = new List<ServerUserMeetingSuggestion>();
                        recommendedSuggestionList.Add(serverSuggestionList[0]);

                        //removing 1st tiem from suggestion list
                        serverSuggestionList.RemoveAt(0);

                        ////update meeting details with suggested details
                        //editFormdateInput.Value = serverSuggestionList[0]._time;
                        //editFormtimeInput.Value = suggestedDateTime;

                        //show pop up with suggestion
                        popup.Height = 300;
                        popup.Width = 400;
                        popup.VerticalOffset = 100;
                        GetSuggestionPopup control = new GetSuggestionPopup();
                        popup.Child = control;
                        popup.IsOpen = true;

                        //set text to show suggestion datetime & location

                        control.suggestedMeetingItemLabel.Text = "Alternative Meeting Time/Location in decending order";
                        control.recommendedMeetingItemListBox.ItemsSource = recommendedSuggestionList;
                        control.suggestedMeetingItemListBox.ItemsSource = serverSuggestionList;

                        control.btnOK.Click += (s, args) =>
                        {
                            popup.IsOpen = false;
                        };

                        control.recommendedMeetingItemListBox.SelectionChanged += (s, args) =>
                            {
                                selectedSuggestion = control.recommendedMeetingItemListBox.SelectedItem as ServerUserMeetingSuggestion;
                                
                                string time = Convert.ToDateTime(selectedSuggestion._time).ToShortTimeString();
                                editFormtimeInput.Value = Convert.ToDateTime(time);
                                editFormdateInput.Value = Convert.ToDateTime(selectedSuggestion._time).Date;
                                editFormLocationInput.Text = selectedSuggestion._location;
                            };
                        control.suggestedMeetingItemListBox.SelectionChanged += (s, args) =>
                        {
                            selectedSuggestion = control.suggestedMeetingItemListBox.SelectedItem as ServerUserMeetingSuggestion;

                            string time = Convert.ToDateTime(selectedSuggestion._time).ToShortTimeString();
                            editFormtimeInput.Value = Convert.ToDateTime(time);
                            editFormdateInput.Value = Convert.ToDateTime(selectedSuggestion._time).Date;
                            editFormLocationInput.Text = selectedSuggestion._location;
                        };

                    }
                };
                getMeetingSuggestion.DownloadStringAsync(new Uri(StringConstants._serverAddress + StringConstants._getMeetingSuggestionAPI + received._editFormItemSelected._meetingItemID, UriKind.Absolute));
            }
            else
            {
                //show pop up with suggestion
                popup.Height = 300;
                popup.Width = 400;
                popup.VerticalOffset = 100;
                EditMeetingFormPopup control = new EditMeetingFormPopup();
                popup.Child = control;
                popup.IsOpen = true;

                //set text to show suggestion datetime & location
                control.messageBox.Text = StringConstants.meetingSuggestionNotSubmittedMsg;
                
                control.btnOK.Click += (s, args) =>
                {
                    popup.IsOpen = false;
                };
            }
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            // If the currently displayed dialog is a pop-up, dialog etc., and
            // a Back Key Press occurs, then "close" the pop-up or dialog, and prevent GoBack.

            if (popup.IsOpen == true)
            {
                popup.IsOpen = false;                   // Hide the popup
                e.Cancel = true;                    // Cancel subsequent BackKey navigation
                LayoutRoot.IsHitTestVisible = true; // Restore mouse hit on main page
            }

            base.OnBackKeyPress(e); // Call base
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ServerUserMeetingSuggestion data = (sender as Button).DataContext as ServerUserMeetingSuggestion;
            ListBoxItem pressedItem = this.editFormNewSuggestionList.ItemContainerGenerator.ContainerFromItem(data) as ListBoxItem;
            if (pressedItem != null)
            {
               newUserSuggestionList.Remove(data);

            }
        }




    }
}